﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MetaSharp.Transformation.Patterns
{
    public delegate Task<IMatch> PropertyPatternMatch(IScope scope, object instance);
    public class PropertyPattern
    {
        public string Name { get; private set; }
        public Pattern Pattern { get; private set; }
        public PropertyPattern(string name, Pattern pattern)
        {
            this.Name = name;
            this.Pattern = pattern;
        }

        public PropertyPatternMatch Compile()
        {
            var p = Pattern != null
                ? Pattern.Compile()
                : null;

            return (s, i) => Target(s, i, Name, p);
        }

        private static async Task<IMatch> Target(IScope scope, object instance, string name, PatternMatch pattern)
        {
            var p = instance.GetType().GetProperty(name);
            if (p == null)
                return await Transformation.Match.Fail(scope);

            var propVal = p.GetValue(instance, null);
            if (pattern != null)
            {
                var propScope = new Scope(new Stream(new object[] { propVal }));
                return await pattern(propScope);
            }

            return await Transformation.Match.Default(scope);
        }
    }
}
